package com.qing.microservices.nacosconsumer.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;

/**
 * @author guoqf
 * @date 2021/3/29 15:00
 */
@RestController
public class HelloController {

    @Autowired
    private DiscoveryClient discoveryClient;


    @Autowired
    private RestTemplate restTemplate;

    private String serviceName = "service-provider";

    @GetMapping("/info")
    public String info() {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        StringBuilder sb = new StringBuilder();
        sb.append("Services: ").append(discoveryClient.getServices()).append("<br/>");
        sb.append("All instances list: <br/>");
        instances.forEach(instance -> {
            sb.append("   host: ").append(instance.getHost())
                    .append(",   port: ").append(instance.getPort()).append("<br/>");
        });
        return sb.toString();
    }

    @GetMapping("/hello")
    public String sayHello() {
        List<ServiceInstance> instances = discoveryClient.getInstances(serviceName);
        ServiceInstance serviceInstance = instances.stream().findAny().orElseThrow(() -> new IllegalStateException("No any available service of " + serviceName + " found"));
        return restTemplate.getForObject("http://" + serviceInstance.getHost() + ":" + serviceInstance.getPort() + "/echo?name=hello", String.class);
    }
}
